package com.suduku.view.listener.adapter;

import com.suduku.util.PathUtil;
import com.suduku.view.constant.ViewConstant;
import com.suduku.view.data.SudoData;
import lombok.SneakyThrows;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * 功能描述: 窗口 适配器 <br/>
 */
public class SudoFrameAdapter extends WindowAdapter {

    /** 当前游戏文件 */
    private final String currentFile = PathUtil.getAppPath(getClass()) + "/c.txt";

    /**
     * 窗口打开事件
     * 加载未完成的游戏
     */
    @Override
    public void windowOpened(WindowEvent event) {
        File file = new File(currentFile);
        if(file.exists()) {
            // 如果文件存在，则恢复游戏
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
                // 只需读取一行即可
                String str = reader.readLine();
                // 拆分
                String[] split = str.split("\\|");
                // 初始化游戏
                SudoData.initData(split[0]);
                char[] cs = split[1].toCharArray();
                for(int i = 0; i < cs.length; i++) {
                    if(cs[i] != '0') {
                        if(SudoData.sudo.getBoxList().get(i).isBlank()) {
                            SudoData.sudo.getBoxList().get(i).setVAndClear(cs[i] - '0');
                            SudoData.sudo.refreshOtherBox(SudoData.sudo.getBoxList().get(i));
                        }
                        ViewConstant.numberFields[i / 9][i % 9].setText(cs[i] + "");
                    }
                }
                ViewConstant.markAllBut.setEnabled(true);
                ViewConstant.clearMarkBut.setEnabled(true);
                ViewConstant.hintBut.setEnabled(true);
                ViewConstant.calcLabel.setText("                    ");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 窗口关闭事件
     */
    @SneakyThrows
    @Override
    public void windowClosing(WindowEvent event) {
        if(SudoData.sudo != null) {
            File file = new File(currentFile);
            if(!file.exists()) {
                file.createNewFile();
            }
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) {
                String str = SudoData.initSudo + "|" + SudoData.sudo.getBoxList().stream().map(b -> String.valueOf(b.getV())).collect(Collectors.joining());
                writer.write(str);
                writer.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
